package redemo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Phone {
    Lock lock = new ReentrantLock();

    // 锁住了整个对象，所以必然是某个线程一直执行到底
    public void sendMs() {
        lock.lock();
        lock.lock(); // 多少层锁都行，只需要配对
        try {
            System.out.println(Thread.currentThread().getId() + "\t sendMS");
            sendEm();
            sendEm();
            sendEm();
            sendEm();
            sendEm();
            sendEm();
        } finally {
            lock.unlock();
            lock.unlock();
            lock.unlock();
            lock.unlock();
        }
    }

    public void sendEm() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getId() + "\t sendEm");
        } finally {
            lock.unlock();
        }
    }
}

public class ReentrantDemo {
    public static void main(String[] args) {
        Phone phone = new Phone();
        new Thread(phone::sendMs).start();
        new Thread(phone::sendMs).start();
    }
}
